import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.styles import Alignment, Font

def write_to_excel(test_cases, output_file):
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Test_Case"

    headers = ["用例标题", "测试步骤", "测试数据", "预期结果"]
    for col_num, header in enumerate(headers, 1):
        col_letter = get_column_letter(col_num)
        ws[f"{col_letter}1"] = header
        ws[f"{col_letter}1"].font = Font(bold=True)
        ws[f"{col_letter}1"].alignment = Alignment(horizontal="center")

    if test_cases:
        for row_num, test_case in enumerate(test_cases, 2):
            ws[f"A{row_num}"] = test_case.get("title", "")
            ws[f"B{row_num}"] = test_case.get("steps", "")
            ws[f"C{row_num}"] = test_case.get("data", "")
            ws[f"D{row_num}"] = test_case.get("result", "")

    for col_num in range(1, len(headers) + 1):
        max_length = 0
        col_letter = get_column_letter(col_num)
        for cell in ws[col_letter]:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            except:
                pass
        adjusted_width = (max_length + 2) * 1.2
        ws.column_dimensions[col_letter].width = adjusted_width

    wb.save(output_file)
    print(f"成功将测试用例写入Excel文件并保存到：{output_file}")